package java44th.group.service.wx.goods;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import java44th.group.bean.admin.vo.BaseRespVo;
import java44th.group.bean.common.BasePageInfo;
import java44th.group.bean.common.BaseStringUtils;
import java44th.group.bean.po.*;
import java44th.group.bean.wx.vo.goods.GoodsPartListVO;
import java44th.group.bean.wx.vo.goods.WxGoodsRelatedVO;
import java44th.group.bean.wx.vo.goods.category.WxGoodsCategoryVO;
import java44th.group.bean.wx.vo.goods.detail.CommentVO;
import java44th.group.bean.wx.vo.goods.detail.DataVO;
import java44th.group.bean.wx.vo.goods.detail.SpecificationListVO;
import java44th.group.bean.wx.vo.goods.detail.WxGoodsDetailVO;
import java44th.group.bean.wx.vo.goods.list.ListVO;
import java44th.group.bean.wx.vo.goods.list.WxGoodsListVO;
import java44th.group.mapper.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @projectName: project-second
 * @package: java44th.group.service.wx.goods
 * @className: WxGoodsServiceImpl
 * @author: 杨浩祥
 * @description: TODO
 * @date: 2022/10/14 19:56
 * @version: 1.0
 */
@Service
public class WxGoodsServiceImpl implements WxGoodsService {


    @Autowired
    MarketGoodsMapper goodsMapper;

    @Autowired
    MarketCategoryMapper categoryMapper;

    @Autowired
    MarketGoodsAttributeMapper attributeMapper;

    @Autowired
    MarketBrandMapper brandMapper;

    @Autowired
    MarketCommentMapper commentMapper;

    @Autowired
    MarketOrderGoodsMapper orderGoodsMapper;

    @Autowired
    MarketUserMapper userMapper;

    @Autowired
    MarketIssueMapper issueMapper;

    @Autowired
    MarketGoodsProductMapper goodsProductMapper;

    @Autowired
    MarketGoodsSpecificationMapper goodsSpecificationMapper;

    @Autowired
    MarketCollectMapper collectMapper;

    @Autowired
    MarketSearchHistoryMapper searchHistoryMapper;

    @Autowired
    MarketFootprintMapper footprintMapper;

    @Override
    public BaseRespVo count() {
        Integer count = goodsMapper.selectCountId();
        return BaseRespVo.ok(count);
    }

    @Transactional
    @Override
    public BaseRespVo list(BasePageInfo info, Integer categoryId, String keyword) {

        // 若登录，且存在关键字,插入关键字
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated() && !BaseStringUtils.isEmpty(keyword)) {
            MarketUser marketUser = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
            MarketSearchHistoryExample marketSearchHistoryExample = new MarketSearchHistoryExample();
            MarketSearchHistoryExample.Criteria criteria = marketSearchHistoryExample.createCriteria();
            criteria.andDeletedEqualTo(false);
            criteria.andKeywordEqualTo(keyword);
            criteria.andUserIdEqualTo(marketUser.getId());
            List<MarketSearchHistory> marketSearchHistorieList = searchHistoryMapper.selectByExample(marketSearchHistoryExample);

            if (marketSearchHistorieList.size() < 1) {
                MarketSearchHistory marketSearchHistory = new MarketSearchHistory();
                marketSearchHistory.setAddTime(new Date());
                marketSearchHistory.setUserId(marketUser.getId());
                marketSearchHistory.setFrom("wx");
                marketSearchHistory.setKeyword(keyword);
                marketSearchHistory.setDeleted(false);
                searchHistoryMapper.insertSelective(marketSearchHistory);
            }
        }


        List<MarketCategory> categoryList = new ArrayList<>();
        MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
        MarketCategoryExample.Criteria criteria = marketCategoryExample.createCriteria();
        criteria.andDeletedEqualTo(false);

        // 先查goodList 通过
        // 如果keyword为空,按照categoryId求

        PageInfo pageInfo = null;
        List<ListVO> list = new ArrayList<ListVO>();
        if (BaseStringUtils.isEmpty(keyword)) {
            PageHelper.startPage(info.getPage(), info.getLimit());
            list = goodsMapper.selectListVOByCategoryId(categoryId);
            pageInfo = new PageInfo(list);
            criteria.andPidNotEqualTo(0);
            categoryList = categoryMapper.selectByExample(marketCategoryExample);
        }
        // 如果keyword不为空，按照keyword求
        if (!BaseStringUtils.isEmpty(keyword)) {
            PageHelper.startPage(info.getPage(), info.getLimit());
            String order = info.getSort() + " " + info.getOrder();
            list = goodsMapper.selectListVOByKeyword("%" + keyword + "%", order);
            pageInfo = new PageInfo(list);
            for (ListVO listVO : list) {
                // criteria.andIdEqualTo(listVO.getCategoryId());
                // listVO.setCategoryId(null);
                // List<MarketCategory> categorieOneList = categoryMapper.selectByExample(marketCategoryExample);
                // categoryList.add(categorieOneList.get(0));
                MarketCategory marketCategory = categoryMapper.selectByPrimaryKey(listVO.getCategoryId());
                listVO.setCategoryId(null);
                if (!categoryList.contains(marketCategory)) {
                    categoryList.add(marketCategory);
                }
            }
            // 如果keyword不为空，且categoryId不为0，按照两者求
            if (categoryId != 0) {
                PageHelper.startPage(info.getPage(), info.getLimit());
                list = goodsMapper.selectListVOByKeywordAndCategoryId("%" + keyword + "%", categoryId, order);
                pageInfo = new PageInfo(list);
            }
        }

        WxGoodsListVO data = WxGoodsListVO.data(pageInfo, categoryList);
        return BaseRespVo.ok(data);
    }

    @Override
    public BaseRespVo category(Integer id) {
        // {"errno":0,"data":{"currentCategory":{"id":1008008,"name":"被枕","keywords":"","desc":"守护你的睡眠时光","pid":1005000,"iconUrl":"http://yanxuan.nosdn.127.net/927bc33f7ae2895dd6c11cf91f5e3228.png","picUrl":"http://yanxuan.nosdn.127.net/b43ef7cececebe6292d2f7f590522e05.png","level":"L2","sortOrder":2,"addTime":"2018-02-01 00:00:00","updateTime":"2018-02-01 00:00:00","deleted":false},"brotherCategory":[{"id":1008008,"name":"被枕","keywords":"","desc":"守护你的睡眠时光","pid":1005000,"iconUrl":"http://yanxuan.nosdn.127.net/927bc33f7ae2895dd6c11cf91f5e3228.png","picUrl":"http://yanxuan.nosdn.127.net/b43ef7cececebe6292d2f7f590522e05.png","level":"L2","sortOrder":2,"addTime":"2018-02-01 00:00:00","updateTime":"2018-02-01 00:00:00","deleted":false},{"id":1008009,"name":"床品件套","keywords":"","desc":"MUJI等品牌制造商出品","pid":1005000,"iconUrl":"http://yanxuan.nosdn.127.net/243e5bf327a87217ad1f54592f0176ec.png","picUrl":"http://yanxuan.nosdn.127.net/81f671bd36bce05d5f57827e5c88dd1b.png","level":"L2","sortOrder":4,"addTime":"2018-02-01 00:00:00","updateTime":"2018-02-01 00:00:00","deleted":false},{"id":1008016,"name":"灯具","keywords":"","desc":"一盏灯，温暖一个家","pid":1005000,"iconUrl":"http://yanxuan.nosdn.127.net/c48e0d9dcfac01499a437774a915842b.png","picUrl":"http://yanxuan.nosdn.127.net/f702dc399d14d4e1509d5ed6e57acd19.png","level":"L2","sortOrder":8,"addTime":"2018-02-01 00:00:00","updateTime":"2018-02-01 00:00:00","deleted":false},{"id":1010003,"name":"地垫","keywords":"","desc":"家里的第“五”面墙","pid":1005000,"iconUrl":"http://yanxuan.nosdn.127.net/83d4c87f28c993af1aa8d3e4d30a2fa2.png","picUrl":"http://yanxuan.nosdn.127.net/1611ef6458e244d1909218becfe87c4d.png","level":"L2","sortOrder":5,"addTime":"2018-02-01 00:00:00","updateTime":"2018-02-01 00:00:00","deleted":false},{"id":1011003,"name":"床垫","keywords":"","desc":"承托你的好时光","pid":1005000,"iconUrl":"http://yanxuan.nosdn.127.net/316afeb3948b295dfe073e4c51f77a42.png","picUrl":"http://yanxuan.nosdn.127.net/d6e0e84961032fc70fd52a8d4d0fb514.png","level":"L2","sortOrder":3,"addTime":"2018-02-01 00:00:00","updateTime":"2018-02-01 00:00:00","deleted":false},{"id":1011004,"name":"家饰","keywords":"","desc":"装饰你的家","pid":1005000,"iconUrl":"http://yanxuan.nosdn.127.net/ab0df9445d985bf6719ac415313a8e88.png","picUrl":"http://yanxuan.nosdn.127.net/79275db76b5865e6167b0fbd141f2d7e.png","level":"L2","sortOrder":9,"addTime":"2018-02-01 00:00:00","updateTime":"2018-02-01 00:00:00","deleted":false},{"id":1015000,"name":"家具","keywords":"","desc":"大师级工艺","pid":1005000,"iconUrl":"http://yanxuan.nosdn.127.net/4f00675caefd0d4177892ad18bfc2df6.png","picUrl":"http://yanxuan.nosdn.127.net/d5d41841136182bf49c1f99f5c452dd6.png","level":"L2","sortOrder":7,"addTime":"2018-02-01 00:00:00","updateTime":"2018-02-01 00:00:00","deleted":false},{"id":1017000,"name":"宠物","keywords":"","desc":"抑菌除味，打造宠物舒适空间","pid":1005000,"iconUrl":"http://yanxuan.nosdn.127.net/a0352c57c60ce4f68370ecdab6a30857.png","picUrl":"http://yanxuan.nosdn.127.net/dae4d6e89ab8a0cd3e8da026e4660137.png","level":"L2","sortOrder":10,"addTime":"2018-02-01 00:00:00","updateTime":"2018-02-01 00:00:00","deleted":false},{"id":1036000,"name":"夏凉","keywords":"","desc":"夏凉床品，舒适一夏","pid":1005000,"iconUrl":"http://yanxuan.nosdn.127.net/13ff4decdf38fe1a5bde34f0e0cc635a.png","picUrl":"http://yanxuan.nosdn.127.net/bd17c985bacb9b9ab1ab6e9d66ee343c.png","level":"L2","sortOrder":1,"addTime":"2018-02-01 00:00:00","updateTime":"2018-02-01 00:00:00","deleted":false}],"parentCategory":{"id":1005000,"name":"生活","keywords":"11","desc":"生活，生活","pid":0,"iconUrl":"http://yanxuan.nosdn.127.net/a45c2c262a476fea0b9fc684fed91ef5.png","picUrl":"http://yanxuan.nosdn.127.net/e8bf0cf08cf7eda21606ab191762e35c.png","level":"L1","sortOrder":2,"addTime":"2018-02-01 00:00:00","updateTime":"2022-10-12 21:38:32","deleted":false}},"errmsg":"成功"}
        MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
        MarketCategoryExample.Criteria criteria = marketCategoryExample.createCriteria();
        WxGoodsCategoryVO wxGoodsCategoryVO = new WxGoodsCategoryVO();
        criteria.andDeletedEqualTo(false);

        MarketCategory marketCategory = categoryMapper.selectByPrimaryKey(id);

        if (marketCategory.getPid() == 0) {
            wxGoodsCategoryVO.setParentCategory(marketCategory);
            criteria.andPidEqualTo(id);
            List<MarketCategory> categoryList = categoryMapper.selectByExample(marketCategoryExample);
            wxGoodsCategoryVO.setCurrentCategory(categoryList.get(0));
            wxGoodsCategoryVO.setBrotherCategory(categoryList);
            return BaseRespVo.ok(wxGoodsCategoryVO);
        }

        wxGoodsCategoryVO.setCurrentCategory(marketCategory);
        criteria.andPidEqualTo(marketCategory.getPid());
        List<MarketCategory> categoryList = categoryMapper.selectByExample(marketCategoryExample);
        wxGoodsCategoryVO.setBrotherCategory(categoryList);
        MarketCategory parrentCategory = categoryMapper.selectByPrimaryKey(marketCategory.getPid());
        wxGoodsCategoryVO.setParentCategory(parrentCategory);
        return BaseRespVo.ok(wxGoodsCategoryVO);
    }

    @Override
    public BaseRespVo detail(Integer id) {
        // {"errno":0,"data":{"specificationList":[{"name":"规格","valueList":[{"id":356,"goodsId":1181075,"specification":"规格","value":"豪华版","picUrl":"http://182.92.235.201:8083/wx/storage/fetch/e2fh9s4h3zn7bf8kfzng.gif","addTime":"2022-09-12 09:41:19","updateTime":"2022-09-12 09:41:19","deleted":false}]},{"name":"颜色","valueList":[{"id":357,"goodsId":1181075,"specification":"颜色","value":"银白","picUrl":"http://182.92.235.201:8083/wx/storage/fetch/osz3b0myh8i15ho2vnvy.jpg","addTime":"2022-09-12 09:41:19","updateTime":"2022-09-12 09:41:19","deleted":false}]},{"name":"形状","valueList":[{"id":358,"goodsId":1181075,"specification":"形状","value":"柜型","picUrl":"http://182.92.235.201:8083/wx/storage/fetch/g0u5dc7zi9yi1h7zjhsr.jpg","addTime":"2022-09-12 09:41:19","updateTime":"2022-09-12 09:41:19","deleted":false}]}],"groupon":[],"issue":[{"id":1,"question":"购买运费如何收取？1","answer":"单笔订单金额（不含运费）满88元免邮费；不满88元，每单收取10元运费。\n(港澳台地区需满10\n加十块1\n加1000","addTime":"2018-02-01 00:00:00","updateTime":"2022-09-08 17:39:44","deleted":false},{"id":2,"question":"使用什么快递发货？","answer":"严选默认使用顺丰快递发货（个别商品使用其他快递），配送范围覆盖全国大部分地区（港澳台地区除","addTime":"2018-02-01 00:00:00","updateTime":"2022-09-08 09:13:23","deleted":false},{"id":3,"question":"如何申请退货？","answer":"1.自收到商品之日起30日内，顾客可申请无忧退货，退款将原路返还，不同的银行处理时间不同，","addTime":"2018-02-01 00:00:00","updateTime":"2018-02-01 00:00:00","deleted":false},{"id":17,"question":"你好","answer":"要讲礼貌123123","addTime":"2022-09-07 21:37:46","updateTime":"2022-09-12 22:04:13","deleted":false}],"userHasCollect":0,"shareImage":"","comment":{"data":[{"addTime":"2022-10-15 11:44:56","picList":[],"adminContent":"","nickname":"user123","id":1148,"avatar":"","content":"这里是测试评价"},{"addTime":"2022-09-12 16:22:12","picList":[],"adminContent":"","nickname":"yangyq","id":1085,"avatar":"https://yanxuan.nosdn.127.net/80841d741d7fa3073e0ae27bf487339f.jpg?imageView&quality=90&thumbnail=64x64","content":"1111"}],"count":2},"share":false,"attribute":[{"id":957,"goodsId":1181075,"attribute":"50×50cm","value":"这是参数值","addTime":"2022-09-12 09:41:19","updateTime":"2022-09-12 09:41:19","deleted":false}],"brand":{"id":1001008,"name":"膳魔师制造商","desc":"严选深入保温行业内部，\n找到德国膳魔师制造商的代工厂。\n同样的品质，却有更优的价格。","picUrl":"http://yanxuan.nosdn.127.net/5fd51e29b9459dae7df8040c8219f241.png","sortOrder":40,"floorPrice":45.00,"addTime":"2018-02-01 00:00:00","updateTime":"2018-02-01 00:00:00","deleted":false},"productList":[{"id":341,"goodsId":1181075,"specifications":["豪华版","银白","柜型"],"price":299.00,"number":975,"url":"http://182.92.235.201:8083/wx/storage/fetch/5dymhtnqxwdmq3u067w7.jpg","addTime":"2022-09-12 09:41:19","updateTime":"2022-10-14 23:07:14","deleted":false}],"info":{"id":1181075,"goodsSn":"10030611","name":"这是名称（测试）","categoryId":1005002,"brandId":1001008,"gallery":["http://182.92.235.201:8083/wx/storage/fetch/adkeif7k3ilp8rxx42zc.jpg"],"keywords":"这是关键字","brief":"这是商品简介","isOnSale":true,"sortOrder":100,"picUrl":"http://182.92.235.201:8083/wx/storage/fetch/34zj1vd7yp3lahzajd8k.jpg","shareUrl":"","isNew":true,"isHot":false,"unit":"台","counterPrice":599.00,"retailPrice":299.00,"addTime":"2022-09-12 09:41:19","updateTime":"2022-09-12 09:42:37","deleted":false,"detail":"<p>这是商品详细介绍</p>\n<p><img src=\"http://182.92.235.201:8083/wx/storage/fetch/jzi8npmchvej455icamw.jpg\" alt=\"\" width=\"292\" height=\"224\" /></p>"}},"errmsg":"成功"}

        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            MarketUser marketUser = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
            MarketFootprint marketFootprint = new MarketFootprint();
            marketFootprint.setAddTime(new Date());
            marketFootprint.setDeleted(false);
            marketFootprint.setUserId(marketUser.getId());
            marketFootprint.setGoodsId(id);
            footprintMapper.insertSelective(marketFootprint);
        }


        WxGoodsDetailVO wxGoodsDetailVO = new WxGoodsDetailVO();

        MarketGoodsAttributeExample attributeExample = new MarketGoodsAttributeExample();
        MarketGoodsAttributeExample.Criteria attributeCriteria = attributeExample.createCriteria();
        attributeCriteria.andGoodsIdEqualTo(id);
        attributeCriteria.andDeletedEqualTo(false);
        List<MarketGoodsAttribute> attributeList = attributeMapper.selectByExample(attributeExample);
        wxGoodsDetailVO.setAttribute(attributeList);

        MarketGoods marketGoods = goodsMapper.selectByPrimaryKey(id);
        MarketBrand marketBrand = brandMapper.selectByPrimaryKey(marketGoods.getBrandId());
        if (marketBrand == null) {
            marketBrand = new MarketBrand();
        }
        wxGoodsDetailVO.setBrand(marketBrand);

        MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria orderGoodsExampleCriteria = orderGoodsExample.createCriteria();
        orderGoodsExampleCriteria.andDeletedEqualTo(false);
        orderGoodsExampleCriteria.andGoodsIdEqualTo(id);
        List<MarketOrderGoods> marketOrderGoodsList = orderGoodsMapper.selectByExample(orderGoodsExample);
        MarketCommentExample marketCommentExample = new MarketCommentExample();
        MarketCommentExample.Criteria commentExampleCriteria = marketCommentExample.createCriteria();
        commentExampleCriteria.andDeletedEqualTo(false);
        List<DataVO> dataVOList = new ArrayList<>();
        for (MarketOrderGoods marketOrderGoods : marketOrderGoodsList) {
            Integer commentId = marketOrderGoods.getComment();
            if (commentId < 1) {
                continue;
            }
            commentExampleCriteria.andIdEqualTo(commentId);
            commentExampleCriteria.andDeletedEqualTo(false);
            List<MarketComment> list = commentMapper.selectByExample(marketCommentExample);

            MarketComment marketComment = list.get(0);
            String content = marketComment.getContent();
            Date addTime = marketComment.getAddTime();
            String adminContent = marketComment.getAdminContent();
            String[] picUrls = marketComment.getPicUrls();

            Integer userId = marketComment.getUserId();
            MarketUser marketUser = userMapper.selectByPrimaryKey(userId);
            String avatar = marketUser.getAvatar();
            String nickname = marketUser.getNickname();

            DataVO dataVO = new DataVO(addTime, adminContent, nickname, commentId, avatar, content, Arrays.asList(picUrls));
            dataVOList.add(dataVO);
        }
        CommentVO commentVO = new CommentVO();
        commentVO.setCount(dataVOList.size());
        commentVO.setData(dataVOList);
        wxGoodsDetailVO.setComment(commentVO);

        wxGoodsDetailVO.setGroupon(new ArrayList<MarketGroupon>());

        wxGoodsDetailVO.setInfo(marketGoods);

        MarketIssueExample issueExample = new MarketIssueExample();
        MarketIssueExample.Criteria issueExampleCriteria = issueExample.createCriteria();
        issueExampleCriteria.andDeletedEqualTo(false);
        List<MarketIssue> marketIssues = issueMapper.selectByExample(issueExample);
        wxGoodsDetailVO.setIssue(marketIssues);

        MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
        MarketGoodsProductExample.Criteria productExampleCriteria = marketGoodsProductExample.createCriteria();
        productExampleCriteria.andDeletedEqualTo(false);
        productExampleCriteria.andGoodsIdEqualTo(id);
        List<MarketGoodsProduct> marketGoodsProductList = goodsProductMapper.selectByExample(marketGoodsProductExample);
        wxGoodsDetailVO.setProductList(marketGoodsProductList);

        wxGoodsDetailVO.setShare(false);

        wxGoodsDetailVO.setShareImage(marketGoods.getShareUrl());

        MarketCollectExample marketCollectExample = new MarketCollectExample();
        MarketCollectExample.Criteria collectExampleCriteria = marketCollectExample.createCriteria();
        collectExampleCriteria.andDeletedEqualTo(false);
        collectExampleCriteria.andValueIdEqualTo(id);
        collectExampleCriteria.andTypeEqualTo((byte) 0);
        if (subject.getPrincipals() == null) {
            wxGoodsDetailVO.setUserHasCollect(0);
        } else {
            List<MarketCollect> marketCollectList = collectMapper.selectByExample(marketCollectExample);
            if (marketCollectList.size() == 0) {
                wxGoodsDetailVO.setUserHasCollect(0);
            } else {
                wxGoodsDetailVO.setUserHasCollect(1);
            }
        }

        List<SpecificationListVO> specificationList = goodsSpecificationMapper.selectSpecificationListVOByGoodsId(id);
        wxGoodsDetailVO.setSpecificationList(specificationList);


        return BaseRespVo.ok(wxGoodsDetailVO);
    }

    @Override
    public BaseRespVo related(Integer id) {
        MarketGoods marketGoods = goodsMapper.selectByPrimaryKey(id);
        Integer categoryId = marketGoods.getCategoryId();

        PageHelper.startPage(1, 6);
        List<GoodsPartListVO> goodsPartList = goodsMapper.selectGoodsPartListByCategoryId(categoryId);
        PageInfo<GoodsPartListVO> pageInfo = new PageInfo<>(goodsPartList);
        WxGoodsRelatedVO data = WxGoodsRelatedVO.data(pageInfo);
        return BaseRespVo.ok(data);
    }
}
